﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Server.CacheData;
using CPPEI.Coolzon.Service;
using CPPEI.Coolzon.Service.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Server.ServiceImplement
{
    class ReqLoginHandler : BaseHandler<ReqLoginData, RespLoginData>
    {
        public ReqLoginHandler()
            : base(RESPONSE_SCENARIO.CONNENT, RESPONSE_COMMAND.CONNECT.LOGIN)
        {
        }

        protected override RespLoginData OnHandle(Data.MainServiceData.Request request, ReqLoginData data)
        {
            if (string.IsNullOrEmpty(data.UserAccount))
            {
                Logger.ErrorToTag("MainService", string.Format("用户{0}登陆失败,账号为空", data.UserAccount));

                return new RespLoginData(false, "账号为空");
            }

            // 检查用户是否存在
            string userIdentity = string.Format("{0}{1}", data.AppType, data.UserAccount);

            Client client = CacheData.ServerData.Instance.GetClient(userIdentity);
            if (client != null && client.AppType == data.AppType)
            {
                if (!CacheData.CacheDataUtil.RemoveClientIfTimeout(CacheData.ServerData.Instance, client))
                {
                    Logger.ErrorToTag("MainService", string.Format("用户{0}登陆失败,该账号已登录", data.UserAccount));
                    return new RespLoginData(false, "账号已登录");
                }
                else
                {
                    Logger.ErrorToTag("MainService", string.Format("用户{0}已登录,但是该账号已超时，删除登录状态，继续执行登录操作", client.UserAccount));
                }
            }
            if(string.Equals(data.AppType, "ConsoleApp"))
            {
                string Uid = System.Configuration.ConfigurationManager.AppSettings["Uid"];
                string Pwd = System.Configuration.ConfigurationManager.AppSettings["Pwd"];
                if (!string.Equals(data.UserAccount, Uid) || !string.Equals(data.UserPassword, Pwd))
                {
                    Logger.ErrorToTag("MainService", string.Format("用户{0}登陆失败,账号或密码错误", data.UserAccount));

                    return new RespLoginData(false, "账号或密码错误");
                }
            }

            client = new Client();
            client.UserIdentity = userIdentity;
            client.UserAccount = data.UserAccount;
            //client.UserId = 
            client.Callback = OperationContext.Current.GetCallbackChannel<IMainServiceCallback>();
            client.AppType = data.AppType;
            client.AppVersion = data.AppVersion;
            client.LatestActiveTicks = DateTime.Now.Ticks;
            
            // 自动选择方案模式
            if (data.SolutionSelectionMode == "ASM")
            {
                client.State = ClientState.Waiting;
            }

            if (ServerData.Instance.AddClient(client))
            {
                RespLoginData responseData = new RespLoginData(true, "登录成功");
                responseData.UserIdentity = client.UserIdentity;
                responseData.Index = client.Index;
                responseData.UserName = data.UserAccount;

                Logger.InfoToTag("MainService", string.Format("用户{0}登陆成功,Identity:{1},Index:{2}", data.UserAccount, client.UserIdentity, client.Index));
                return responseData;
            }
            else
            {
                Logger.ErrorToTag("MainService", string.Format("用户{0}登陆失败,无法添加到用户列表，用户已达最大数量", data.UserAccount));
                return null;
            }
        }
    }
}
